package com.chefu.evaluation.service.impl;

import com.chefu.common.exception.CfException;
import com.chefu.common.exception.ExceptionEnum;
import com.chefu.common.pojo.PageResult;
import com.chefu.common.utils.BeanHelper;
import com.chefu.evaluation.dto.POContentDTO;
import com.chefu.evaluation.dto.POProContentDTO;
import com.chefu.evaluation.pojo.PartsOrderEval;
import com.chefu.evaluation.pojo.PartsProviderInfo;
import com.chefu.evaluation.service.PartsOrderEvalService;
import com.chefu.evaluation.vo.ContentVO;
import com.chefu.evaluation.vo.POProSearchVO;
import com.chefu.evaluation.vo.POSearchVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

@Service
public class PartsOrderEvalServiceImpl implements PartsOrderEvalService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public PageResult<PartsOrderEval> findByPage(Integer pageNum, Integer pageSize, POSearchVO poSearchVO) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, sort);
        Query query = new Query();
        if (StringUtils.isNotEmpty(poSearchVO.getOrderId())) {
            Pattern pattern = Pattern.compile("^.*"+ poSearchVO.getOrderId() +".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("orderId").regex(pattern));
        }
        if (StringUtils.isNotEmpty(poSearchVO.getCarOwner())) {
            query.addCriteria(Criteria.where("carOwnerName").regex(".*?\\" + poSearchVO.getCarOwner() + ".*"));
        }
        if (StringUtils.isNotEmpty(poSearchVO.getPartsProvider())) {
            query.addCriteria(Criteria.where("providerName").regex(".*?\\" + poSearchVO.getPartsProvider() + ".*"));
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (StringUtils.isNotEmpty(poSearchVO.getStartTime()) && StringUtils.isEmpty(poSearchVO.getEndTime())) {
            try {
                Date startTime = simpleDateFormat.parse(poSearchVO.getStartTime());
                query.addCriteria(Criteria.where("orderTime").gte(startTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotEmpty(poSearchVO.getEndTime()) && StringUtils.isEmpty(poSearchVO.getStartTime())) {
            try {
                Date endTime = simpleDateFormat.parse(poSearchVO.getEndTime());
                endTime = nextDay(endTime);
                query.addCriteria(Criteria.where("orderTime").lt(endTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotEmpty(poSearchVO.getStartTime()) && StringUtils.isNotEmpty(poSearchVO.getEndTime())) {
            try {
                Date startTime = simpleDateFormat.parse(poSearchVO.getStartTime());
                Date endTime = simpleDateFormat.parse(poSearchVO.getEndTime());
                endTime = nextDay(endTime);
                query.addCriteria(Criteria.where("orderTime").gte(startTime).lt(endTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        //总条数
        Long total = mongoTemplate.count(query, PartsOrderEval.class);
        //查询记录
        List<PartsOrderEval> partsOrderEvals = mongoTemplate.find(query.with(pageable), PartsOrderEval.class);
        Long totalPage = (total - 1) / pageSize + 1;
        return new PageResult<PartsOrderEval>(total, totalPage, partsOrderEvals);
    }

    private Date nextDay(Date date){
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, 1);
        return calendar.getTime();
    }

    @Override
    public void saveEvaluation(String orderId, ContentVO poContentVO) {
        //todo 调用部件订单的接口查询订单相关内容
        try {
            PartsOrderEval partsOrderEval = new PartsOrderEval();
            partsOrderEval.setOrderId(orderId);
            //根据orderId查询部件订单
            partsOrderEval.setProviderId("1376949130777145344");
            partsOrderEval.setProviderName("海德汉");
            //获取订单时间
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date orderTime = simpleDateFormat.parse("2021-02-25");
            partsOrderEval.setOrderTime(orderTime);

            partsOrderEval.setCreateTime(new Date());

            //从token中获取车主信息
            partsOrderEval.setCarOwnerId("1376949206748610560");
            partsOrderEval.setCarOwnerName("大狐狸");

            //获取提交的评价信息
            partsOrderEval.setScores(poContentVO.getScores());
            Double[] scores = poContentVO.getScores();
            Integer contentScore = ((int) (scores[0] + scores[1] + scores[2]) * 2) / 3;
            partsOrderEval.setScore(contentScore / 2.0);
            partsOrderEval.setContent(poContentVO.getContent());
            String[] evalImages = poContentVO.getImages().split(",");
            partsOrderEval.setImages(evalImages);

            //从订单id获取配件id
            partsOrderEval.setPartsItem("机油");
            //从订单获取信息 tb_auto_parts_order表的actual_fee
            partsOrderEval.setTotalFee(45.5);
            partsOrderEval.setState("0");
            mongoTemplate.save(partsOrderEval);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new CfException(ExceptionEnum. INSERT_OPERATION_FAIL);
        }
    }

    @Override
    public PageResult<POContentDTO> findByCarOwner(Integer pageNum, Integer pageSize) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, sort);
        Query query = new Query();
        //todo 从token中获取车主的信息 暂时写死
        query.addCriteria(Criteria.where("carOwnerId").is("1376949206748610560"));
        //总条数
        Long total = mongoTemplate.count(query, PartsOrderEval.class);
        //查询记录
        List<PartsOrderEval> partsOrderEvals = mongoTemplate.find(query.with(pageable), PartsOrderEval.class);
        List<POContentDTO> poContentDTOS = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (PartsOrderEval partsOrderEval : partsOrderEvals) {
            POContentDTO poContentDTO = BeanHelper.copyProperties(partsOrderEval, POContentDTO.class);
            Date createTime = partsOrderEval.getCreateTime();
            poContentDTO.setTime(sdf.format(createTime));
            String providerId = partsOrderEval.getProviderId();
            PartsProviderInfo providerInfo = mongoTemplate.findOne(
                    new Query().addCriteria(Criteria.where("providerId").is(providerId)), PartsProviderInfo.class);
            poContentDTO.setPartsProInfo(providerInfo);
            poContentDTOS.add(poContentDTO);
        }
        Long totalPage = (total - 1) / pageSize + 1;
        return new PageResult<POContentDTO>(total, totalPage, poContentDTOS);
    }

    @Override
    public PageResult<POProContentDTO> findByPartsProvider(Integer pageNum, Integer pageSize, POProSearchVO poProSearchVO) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, sort);
        Query query = new Query();

        //todo 根据token获取用户id，查询用户所在的配件商id
        query.addCriteria(Criteria.where("providerId").is("1376948079898460160"));
        if (StringUtils.isNotEmpty(poProSearchVO.getCarOwner())) {
            query.addCriteria(Criteria.where("carOwnerName").regex(".*?\\" + poProSearchVO.getCarOwner() + ".*"));
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (StringUtils.isNotEmpty(poProSearchVO.getStartTime()) && StringUtils.isEmpty(poProSearchVO.getEndTime())) {
            try {
                Date startTime = simpleDateFormat.parse(poProSearchVO.getStartTime());
                query.addCriteria(Criteria.where("createTime").gte(startTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotEmpty(poProSearchVO.getEndTime()) && StringUtils.isEmpty(poProSearchVO.getStartTime())) {
            try {
                Date endTime = simpleDateFormat.parse(poProSearchVO.getEndTime());
                endTime = nextDay(endTime);
                query.addCriteria(Criteria.where("createTime").lt(endTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotEmpty(poProSearchVO.getStartTime()) && StringUtils.isNotEmpty(poProSearchVO.getEndTime())) {
            try {
                Date startTime = simpleDateFormat.parse(poProSearchVO.getStartTime());
                Date endTime = simpleDateFormat.parse(poProSearchVO.getEndTime());
                endTime = nextDay(endTime);
                query.addCriteria(Criteria.where("createTime").gte(startTime).lt(endTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        //总条数
        Long total = mongoTemplate.count(query, PartsOrderEval.class);
        //查询记录
        List<PartsOrderEval> partsOrderEvals = mongoTemplate.find(query.with(pageable), PartsOrderEval.class);
        List<POProContentDTO> poProContentDTOS = BeanHelper.copyWithCollection(partsOrderEvals, POProContentDTO.class);
        Long totalPage = (total - 1) / pageSize + 1;
        return new PageResult<POProContentDTO>(total, totalPage, poProContentDTOS);
    }

    @Override
    public void deleteEvaluation(String id) {
        PartsOrderEval orderEval = mongoTemplate.findOne(new Query().addCriteria(Criteria.where("id").is(id)), PartsOrderEval.class);
        if (orderEval == null) {
            throw new CfException(ExceptionEnum.DELETE_OPERATION_FAIL);
        }
        //todo  根据token获取用户信息，判断用户是否具备运营角色
        if (true) {
            mongoTemplate.remove(new Query().addCriteria(Criteria.where("id").is(id)), PartsOrderEval.class);
        } else {
            throw new CfException(ExceptionEnum.DELETE_OPERATION_FAIL);
        }
    }
}
